import axios from "axios";
// import { Toast } from "antd-mobile";
// import { makeSign } from "../utils/sign.js";   // 如需签名，解开此行
// import { s_key } from "./config";              // 你的密钥
import { dialog } from '@/utils/dialog'
// 1. 创建 axios 实例
const service = axios.create({
  // baseURL: "http://192.168.1.153:8000/api/",
  baseURL: "https://api.nextai.club/api/",
  timeout: 300000,
  headers: {
    "Content-Type": "application/json",
    "Lang": "zh",
  },
});

/** 工具：判断是否 FormData */
const isFormData = (v: any): v is FormData =>
  typeof FormData !== "undefined" && v instanceof FormData;

/** 工具：给 params/data 补时间戳，并返回用于签名的纯对象 */
function attachTimestampAndGetSignBase(
  method: string | undefined,
  paramsOrData: any
) {
  const timestamp = Math.floor(Date.now() / 1000);

  // GET/DELETE 用 params，其它用 data
  const isQuery = method === "get" || method === "delete";

  // 如果是 FormData，需要 append
  if (isFormData(paramsOrData)) {
    paramsOrData.append("_t", String(timestamp));
    // 构造用于签名的纯对象（从 FormData 提取）
    const signBase: Record<string, any> = {};
    for (const [k, v] of paramsOrData.entries()) signBase[k] = v;
    return { signBase, carrier: paramsOrData, isQuery };
  }

  // 普通对象
  const carry = paramsOrData || {};
  carry._t = timestamp;
  return { signBase: { ...carry }, carrier: carry, isQuery };
}

// 2. 请求拦截器
service.interceptors.request.use(
  (config) => {
    const token = localStorage.getItem("token");
    if (token) {
      (config.headers as any).Authorization = "Bearer " + token;
    }

    try {
      // 采集原始 data/params
      const method = (config.method || "get").toLowerCase();
      const rawParams = method === "get" || method === "delete" ? config.params : config.data;

      // 给 data/params 添加 _t，并得到用于签名的纯对象
      const { signBase, carrier, isQuery } = attachTimestampAndGetSignBase(
        method,
        rawParams
      );

      // 写回 config
      if (isQuery) {
        config.params = carrier;
      } else {
        config.data = carrier;
      }

      // 如果是上传（FormData），强制 multipart 头；否则保留默认
      if (!isQuery && isFormData(config.data)) {
        (config.headers as any)["Content-Type"] = "multipart/form-data";
      }

      // === 可选：生成 sign ===
      // const sign = makeSign(signBase, s_key || "okMax_v1");
      // (config.headers as any)["sign"] = sign;

    } catch (err) {
      console.error("生成 sign/_t 出错:", err);
    }

    return config;
  },
  (error) => Promise.reject(error)
);

// 3. 响应拦截器
service.interceptors.response.use(
  (response) => {
    const res = response.data;
    if (res.code) {
      console.error(res.msg || "请求错误");
      // alert(res.msg || "请求错误")
      dialog.alert({message: res.msg || "请求错误"});
      return Promise.reject(res.msg);
    }
    return res.data;
  },
  (error) => {
    console.error("网络错误:", error?.message || error);
    // alert(error?.message || "网络错误")
    dialog.alert({message: error?.message || "网络错误"});
    return Promise.reject(error);
  }
);

// ========= 基础方法 =========
export const get = (url, params: any = {}, config: any = {}) =>
  service.get(url, { params, ...config });

export const post = (url, data: any = {}, config: any = {}) =>
  service.post(url, data, config);

export const put = (url, data: any = {}, config: any = {}) =>
  service.put(url, data, config);

export const patch = (url, data: any = {}, config: any = {}) =>
  service.patch(url, data, config);

export const del = (url, params: any = {}, config: any = {}) =>
  service.delete(url, { params, ...config });

/**
 * 上传文件（图片/视频等）
 * - 默认字段名为 "file"，可通过 options.fieldName 自定义
 * - 支持附带额外表单字段 extraData
 * - 自动继承拦截器（会补 _t、可加 sign），并自动设置 multipart 头
 */
export function upload(
  url: string,
  file: File | Blob | File[] | Blob[] | FormData,
  options?: {
    fieldName?: string; // 默认 "file"
    extraData?: Record<string, any>;
    config?: any; // 透传 axios config，如 { onUploadProgress }
  }
) {
  const fieldName = options?.fieldName || "file";
  const extraData = options?.extraData || {};
  const cfg = options?.config || {};

  let form: FormData;

  if (isFormData(file)) {
    // 已经是 FormData，直接用（拦截器会 append _t）
    form = file;
    // 如果还想追加额外字段
    Object.entries(extraData).forEach(([k, v]) => form.append(k, String(v)));
  } else {
    form = new FormData();

    // 支持传单文件或文件数组
    const files = Array.isArray(file) ? file : [file];
    files.forEach((f, idx) => {
      // 多文件时按 file[0], file[1]… 传；单文件时用 fieldName
      const key = files.length > 1 ? `${fieldName}[${idx}]` : fieldName;
      // 兼容 Blob 场景：提供一个缺省文件名
      if (f instanceof File) {
        form.append(key, f);
      } else {
        form.append(key, f, `blob_${Date.now()}_${idx}.bin`);
      }
    });

    // 附加业务字段
    Object.entries(extraData).forEach(([k, v]) => form.append(k, String(v)));
  }

  return service.post(url, form, {
    ...cfg,
    headers: {
      ...(cfg.headers || {}),
      // 再次显式设置，确保覆盖默认 json 头
      "Content-Type": "multipart/form-data",
    },
  });
}

export default service;
